/**
 * @Author 韦建韩
 * @Date 2022/4/19
 */
package com.example.devops.web.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.devops.Conntext.ResponseContext;
import com.example.devops.Manage.UserManager.UserInfoManage;
import com.example.devops.entity.pojo.User;
import com.example.devops.util.SnowFlake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.Objects;

@Component
public class GetUserInfoFilter implements Filter {
    Logger logger = LoggerFactory.getLogger(GetUserInfoFilter.class);
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse servletResponse1 = (HttpServletResponse) servletResponse;
        ResponseContext.setM(servletResponse1);
        String userStr = httpServletRequest.getHeader("user");
        logger.info("request:{}",userStr);
        if (Objects.nonNull(userStr)) {
            String encode = URLDecoder.decode(userStr, "UTF-8");
            JSONObject jsonObject = JSON.parseObject(encode);
            User user = jsonObject.toJavaObject(User.class);
            logger.info("request user:{}",user.toString());
            UserInfoManage.set(user);
        }
        long id = SnowFlake.nextId();
        String traceId = Long.toString(id);
        MDC.put("traceId", traceId);
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
